<?php
/**
 * BaseApi.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/10/21- 9:38 上午
 */
namespace common\components\api\cloud;

use common\exception\ServicesException;
use GuzzleHttp\Client;
use common\helpers\StringHelper;
use yii\helpers\Json;
use Yii;
class BaseApi
{

    /**
     * 请求newapi
     * @param string $url
     * @param array $args
     * @return mixed
     * @throws ServicesException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function requestApi(string $url,array $args)
    {
        $http = new Client([
            //根域名
            'base_uri' => Yii::$app->params['newapi_url'],
            //超时
            'timeout' => Yii::$app->params['request_timeout'],
            'headers' => [
                'soft' => Yii::$app->params['soft_key']
            ]
        ]);

        $response = $http->request('POST',$url,[
            'form_params' =>$args
        ]);

        if($response->getStatusCode() == 200)
        {
            $responseStr = $response->getBody()->getContents();
            $response = Json::decode($responseStr);

            if(!is_array($response))
            {
                throw new ServicesException('返回格式错误!');
            }

            if(!isset($response['success']))
            {
                throw new ServicesException('请求newapi接口错误');

            }

            return $response['success'];
        }else{
            throw new ServicesException('请求newapi错误，http状态码:'.$response->getStatusCode());
        }
    }


    /**
     * 拿到token
     * @return array
     */
    protected function getToken(int $user_id)
    {
        $nowTime = time();
        $client = $client = StringHelper::getRandomStr(20);
        return [
            'client' => $client,
            'clienttime' =>$nowTime,
            'token'=> md5($client.$nowTime.$user_id.Yii::$app->params['soft_token_sn'])
        ];
    }



    /**
     * 检验code
     * @param string $credentials
     * @return array|false|string
     * @throws ServicesException
     */
    public function checkCode(array $credentials)
    {

        $key = Yii::$app->params['newapi_decode_key'];
        $txt = urldecode($credentials['code']);
        $chars = Yii::$app->params['newapi_decode_code'];
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for($i = 0; $i < strlen($txt); $i++){
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) $j += 64;
            $tmp .= $chars[$j];
        }
        $tmp=base64_decode($tmp);
        $tmp=explode("|",$tmp);
        if(count($tmp)!=2){
            throw new ServicesException('请勿非法操作！');
        }

        //验证字符串有效长度，不同位数的userId长度不同，防止篡改URL参数
        $validLen = 0;
        $userIdLen = strlen($tmp[0]);
        if($userIdLen > 10){
            $validLen = 34;
        }elseif($userIdLen > 7){
            $validLen = 30;
        }elseif($userIdLen > 4){
            $validLen = 26;
        }elseif($userIdLen > 1){
            $validLen = 22;
        }else{
            $validLen = 18;
        }
        //经过%转义的字符每个加2位
        $validLen += substr_count($credentials['code'],'%')*2;
        if($validLen != strlen($credentials['code'])+1){
            throw new ServicesException('请勿非法操作！');
        }

        if($credentials['taobao_user_id'] != $tmp[0] || $credentials['time'] != $tmp[1]){
            throw new ServicesException('校验不通过！');
        }
        return $tmp;

    }


}